package com.wisdytech.linkdcs.tool.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.constants.DictKeyConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.common.utils.ImportExcelUtils;
import com.wisdytech.linkdcs.system.dao.ISysUserDao;
import com.wisdytech.linkdcs.system.model.SysUser;
import com.wisdytech.linkdcs.tool.dao.*;
import com.wisdytech.linkdcs.tool.model.*;
import com.wisdytech.linkdcs.tool.service.ITtEqToolService;
import com.wisdytech.linkdcs.tool.vo.ToolCheckItemVO;
import com.wisdytech.linkdcs.tool.vo.ToolCheckVO;
import com.wisdytech.linkdcs.tool.vo.ToolMaintainItemVO;
import com.wisdytech.linkdcs.tool.vo.ToolMaintainVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhanghailin
 * @since 2018-06-05
 */
@Service
@Transactional
public class TtEqToolServiceImpl extends BaseService<TtEqToolDao, TtEqTool> implements ITtEqToolService {

    @Resource
    private ISysUserDao sysUserDao;

    @Resource
    private TtEqToolDao ttEqToolDao;
    @Resource
    private ToolConfigDao toolConfigDao;
    @Resource
    private ToolMaintainItemDao toolMaintainItemDao;
    @Resource
    private ToolCheckItemDao toolCheckItemDao;
//    @Override
//    public PageInfo<TtEqTool> listToolInfoByFilter(String toolCode,String toolName,String opCode,String toolModel,String status, Filter filter) {
//        Map<String, Object> params = new HashMap<>();
//        List<TtEqTool> list = this.beforeList(TtEqToolDao.class,filter).listToolInfoByFilter(params);
//        PageInfo<TtEqTool> page = new PageInfo<>(list);
//        return page;
//    }


    @Override
    public PageInfo<TtEqTool> listToolInfoByFilter(String toolCode, String toolName, String toolModel, String toolType, String opCode, String toolStatus, String checkDateStart, String checkDateEnd, String maintainFlag, String checkoutFlag, Filter filter) {
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isNotBlank(toolCode)) {
            params.put("toolCode", toolCode);
        }
        if (StringUtils.isNotBlank(toolName)) {
            params.put("toolName", toolName);
        }
        if (StringUtils.isNotBlank(toolModel)) {
            params.put("toolModel", toolModel);
        }
        if (StringUtils.isNotBlank(toolType)) {
            params.put("toolType", toolType);
        }
        if (StringUtils.isNotBlank(opCode)) {
            params.put("opCode", opCode);
        }
        if (StringUtils.isNotBlank(toolStatus)) {
            params.put("toolStatus", toolStatus);
        }
        if (StringUtils.isNotBlank(checkDateStart)) {
            params.put("checkDateStart", checkDateStart);
        }
        if (StringUtils.isNotBlank(checkDateEnd)) {
            params.put("checkDateEnd", checkDateEnd);
        }
        if (StringUtils.isNotBlank(maintainFlag)) {
            params.put("maintainFlag", maintainFlag);
        }
        if (StringUtils.isNotBlank(checkoutFlag)) {
            params.put("checkoutFlag", checkoutFlag);
        }
        List<TtEqTool> list = this.beforeList(TtEqToolDao.class, filter).listToolInfoByFilter(params);
        return new PageInfo<>(list);
    }

    @Override
    public Boolean saveOrUpdateTool(TtEqTool ttEqTool, SysUser operator) {
        Boolean flag = false;
        if (operator == null)
            throw new ServiceException("操作人不能为空");
        if (ttEqTool == null)
            throw new ServiceException("参数错误");

        //校验文档编号是否重复
        EntityWrapper<TtEqTool> ew = new EntityWrapper<>();
        ew.eq("tool_code", ttEqTool.getToolCode());
        ew.eq("del_flag", CommonConstants.DEL_FLAG);
        //修改
        if (StringUtils.isNotBlank(ttEqTool.getPkId())) {
            ew.ne("pk_id", ttEqTool.getPkId());
            Integer count = ttEqToolDao.selectCount(ew);
            if (count > 0) {
                throw new ServiceException("工装编码重复");
            }
            ttEqTool.setUpdateUser(operator.getUsername());
            ttEqTool.setUpdateDate(new Date());

            //TODO 更改周期在下个保养周期再计算
            TtEqTool tool = ttEqToolDao.selectById(ttEqTool.getPkId());
            // 保养状态由否改为是 则修改工装下次保养时间为工装信息中的保养开始时间
            if ("0".equals(tool.getMaintainFlag()) && "1".equals(ttEqTool.getMaintainFlag())) {
                ttEqTool.setNextMaintainDate(ttEqTool.getMaintainDate());
            }
            // 校验状态由否改为是 则修改工装下次校验时间为工装信息中的校验开始时间
            if ("0".equals(tool.getCheckoutFlag()) && "1".equals(ttEqTool.getCheckoutFlag())) {
                ttEqTool.setNextCheckoutDate(ttEqTool.getNextCheckoutDate());
            }

            Integer updateCount = ttEqToolDao.updateById(ttEqTool);
            if (updateCount > 0)
                flag = true;
        } else {
            Integer count = ttEqToolDao.selectCount(ew);
            if (count > 0) {
                throw new ServiceException("工装编码重复");
            }
            ttEqTool.setPkId(BaseUtil.getUUID());
            ttEqTool.setCreateDate(new Date());
            ttEqTool.setCreateUser(operator.getUsername());
            ttEqTool.setDelFlag(CommonConstants.DEL_FLAG);

            //插入下次保养开始时间
            ttEqTool.setNextMaintainDate(ttEqTool.getMaintainDate());
            //插入下次校验开始时间
            ttEqTool.setNextCheckoutDate(ttEqTool.getCheckoutDate());
            Integer insertCount = ttEqToolDao.insert(ttEqTool);
            if (insertCount > 0) {
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public Boolean deleteTool(String pkIds, SysUser operator) {
        if (operator == null)
            throw new ServiceException("操作人不能为空");
        String[] deletePkIds = pkIds.split(",");
        if (deletePkIds.length == 0) return true;
        List<String> idList = new ArrayList<String>();
        String[] id = pkIds.split(",");
        for (int i = 0; i < id.length; i++) {
            idList.add(id[i]);
        }

        for (String pkId : idList) {
            //判断是否配置
            TtEqTool TtEqTool = ttEqToolDao.selectById(pkId);
            EntityWrapper<ToolConfig> ew = new EntityWrapper<>();
            ew.eq("TOOL_CODE", TtEqTool.getToolCode());
            int count = toolConfigDao.selectCount(ew);
            if (count > 0) {
                throw new ServiceException("工装已被配置");
            }
            EntityWrapper<ToolMaintainItem> ew1 = new EntityWrapper<>();
            ew1.eq("TOOL_CODE", TtEqTool.getToolCode());
            ew1.eq("DEL_FLAG",CommonConstants.DEL_FLAG);
            //判断是否添加保养项
            int num = toolMaintainItemDao.selectCount(ew1);
            if (num > 0) {
                throw new ServiceException("工装已添加保养项");
            }
            //判断是否添加校验项
            EntityWrapper<ToolCheckItem> ew2 = new EntityWrapper<>();
            ew2.eq("TOOL_CODE", TtEqTool.getToolCode());
            //判断是否添加保养项
            int num1 = toolCheckItemDao.selectCount(ew2);
            if (num1 > 0) {
                throw new ServiceException("工装已添加校验项");
            }
        }
        List<String> pkIdCollection = Arrays.asList(deletePkIds);
        Integer deleteCount = ttEqToolDao.deleteBatchIds(pkIdCollection);
        return deleteCount > 0;
    }

    @Override
    public TtEqTool getToolInfoById(String pkId) {
        if (StringUtils.isBlank(pkId)) {
            return null;
        }
        return this.ttEqToolDao.getToolInfoById(pkId);
    }

    @Override
    public List<TtEqTool> getToolList(String search) {
        EntityWrapper<TtEqTool> ew = new EntityWrapper<>();
        ew.setSqlSelect("pk_id", "tool_code", "tool_name");
        ew.eq("del_flag", CommonConstants.DEL_FLAG);
        if (StringUtils.isNotBlank(search)) {
            ew.andNew().like("tool_code", search).or().like("tool_name", search);
        }
        return ttEqToolDao.selectList(ew);
    }

    @Override
    public PageInfo<TtEqTool> getToolMaintainList(String toolCode, String toolName, String toolModel, String toolType, String nextMaintainDateStart, String nextMaintainDateEnd, Filter filter) {
        Map<String, Object> params = new HashMap<>();
        params.put("toolTypeParentKey", DictKeyConstants.TOOL_TYPE_PARENT_KEY);
        if (StringUtils.isNotBlank(toolCode)) {
            params.put("toolCode", toolCode);
        }
        if (StringUtils.isNotBlank(toolName)) {
            params.put("toolName", toolName);
        }
        if (StringUtils.isNotBlank(toolModel)) {
            params.put("toolModel", toolModel);
        }
        if (StringUtils.isNotBlank(toolType)) {
            params.put("toolType", toolType);
        }
        if (StringUtils.isNotBlank(nextMaintainDateStart)) {
            params.put("nextMaintainDateStart", nextMaintainDateStart);
        }
        if (StringUtils.isNotBlank(nextMaintainDateEnd)) {
            params.put("nextMaintainDateEnd", nextMaintainDateEnd);
        }
        List<TtEqTool> list = this.beforeList(TtEqToolDao.class, filter).getToolMaintainList(params);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<TtEqTool> getToolCheckList(String toolCode, String toolName, String toolModel, String toolType, String opCode, String nextCheckDateStart, String nextCheckDateEnd, Filter filter) {
        Map<String, Object> params = new HashMap<>();
        params.put("toolTypeParentKey", DictKeyConstants.TOOL_TYPE_PARENT_KEY);
        if (StringUtils.isNotBlank(toolCode)) {
            params.put("toolCode", toolCode);
        }
        if (StringUtils.isNotBlank(toolName)) {
            params.put("toolName", toolName);
        }
        if (StringUtils.isNotBlank(toolModel)) {
            params.put("toolModel", toolModel);
        }
        if (StringUtils.isNotBlank(toolType)) {
            params.put("toolType", toolType);
        }
        if (StringUtils.isNotBlank(opCode)) {
            params.put("opCode", opCode);
        }
        if (StringUtils.isNotBlank(nextCheckDateStart)) {
            params.put("nextCheckDateStart", nextCheckDateStart);
        }
        if (StringUtils.isNotBlank(nextCheckDateEnd)) {
            params.put("nextCheckDateEnd", nextCheckDateEnd);
        }
        List<TtEqTool> list = this.beforeList(TtEqToolDao.class, filter).getToolCheckList(params);
        return new PageInfo<>(list);
    }

    @Override
    public ToolMaintainVO getToolMaintainInfo(String toolCode) {
        if (StringUtils.isBlank(toolCode))
            return null;
        //查询工装基本信息
        TtEqTool toolParams = new TtEqTool();
        toolParams.setToolCode(toolCode);
        toolParams.setDelFlag(CommonConstants.DEL_FLAG);
        TtEqTool toolInfo = ttEqToolDao.selectOne(toolParams);
        if (toolInfo == null)
            throw new ServiceException("工装不存在");
        ToolMaintainVO vo = new ToolMaintainVO();
        vo.setToolCode(toolInfo.getToolCode());
        vo.setToolName(toolInfo.getToolName());

        //查询工装检验项信息
        List<ToolMaintainItemVO> itemList = this.ttEqToolDao.getToolMaintainItemList(toolCode);
        vo.setMaintainItemList(itemList);
        return vo;
    }

    @Override
    public ToolCheckVO getToolCheckInfo(String toolCode) {
        if (StringUtils.isBlank(toolCode))
            return null;
        //查询工装基本信息
        TtEqTool toolParams = new TtEqTool();
        toolParams.setToolCode(toolCode);
        toolParams.setDelFlag(CommonConstants.DEL_FLAG);
        TtEqTool toolInfo = ttEqToolDao.selectOne(toolParams);
        if (toolInfo == null)
            throw new ServiceException("工装不存在");
        ToolCheckVO vo = new ToolCheckVO();
        vo.setToolCode(toolInfo.getToolCode());
        vo.setToolName(toolInfo.getToolName());

        //查询工装检验项信息
        List<ToolCheckItemVO> itemList = this.ttEqToolDao.getToolCheckItemList(toolCode);
        vo.setCheckItemList(itemList);
        return vo;
    }

    @Override
    public PageInfo<SysUser> getUserPageList(String search, Filter filter) {
        EntityWrapper<SysUser> ew = new EntityWrapper<>();
        ew.setSqlSelect("pk_id", "truename", "username", "work_no");
        if (StringUtils.isNotBlank(search)) {
            ew.like("work_no", search);
        }
        ew.eq("del_flag", CommonConstants.DEL_FLAG)
                .orderBy("CREATE_DATE", false);
        //List<SysUser> list = this.beforeList(ISysUserDao.class,filter).selectList(ew);
        List<SysUser> list = sysUserDao.selectList(ew);
        return new PageInfo<>(list);
    }

    @Override
    public void batchImportToolInfo(MultipartFile file, SysUser operator) {
        if (file == null) {
            throw new ServiceException("文件为空");
        }
        if (operator ==null) {
            throw new ServiceException("操作人不能为空");
        }
        int errorRow=0;
        int errorCell=0;
        try {
            String fileName = file.getOriginalFilename();
            InputStream in = file.getInputStream();
            List<List<Object>> data = ImportExcelUtils.getDataListByExcel(in, fileName);
            if (data == null || data.size() == 0) {
                throw new ServiceException("表格数据为空");
            }
            List<TtEqTool> list = new ArrayList<>();

            SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd");
            //i 从1开始，去除表头数据，根据自己的模板而定
            for (int i = 1; i < data.size(); i++) {
                TtEqTool tool = new TtEqTool();
                tool.setCreateDate(new Date());
                tool.setCreateUser(operator.getUsername());
                tool.setDelFlag(CommonConstants.DEL_FLAG);
                tool.setStatus("1");
                errorRow = i;
                tool.setPkId(BaseUtil.getUUID());
                EntityWrapper<TtEqTool> ew = new EntityWrapper<>();
                ew.eq("tool_code", data.get(i).get(0).toString());
                ew.eq("del_flag", CommonConstants.DEL_FLAG);
                Integer count = ttEqToolDao.selectCount(ew);
                if (count > 0) {
                    throw new ServiceException("工装编码重复");
                }
                tool.setToolCode(data.get(i).get(0).toString());
                tool.setToolName(data.get(i).get(1).toString());

                String appModel = data.get(i).get(2).toString();
                TmProductModel tmProductModel = new TmProductModel();
                tmProductModel.setDelFlag(CommonConstants.DEL_FLAG);
                tmProductModel.setProdModelCode(appModel);
                TmProductModel t = tmProductModelDao.selectOne(tmProductModel);
                if(t==null){
                    throw new ServiceException("产品型号编码不存在");
                }
                tool.setApplicationModel(t.getPkId());
                tool.setOpCode(data.get(i).get(3).toString());
                tool.setToolModel(data.get(i).get(4).toString());
                tool.setStandardLife(data.get(i).get(5).toString());
                tool.setStandardLifeUnit(data.get(i).get(6).toString());
                tool.setToolType(data.get(i).get(7).toString());
                tool.setManufactor(data.get(i).get(8).toString());
                tool.setDutyUser(data.get(i).get(9).toString());
                tool.setFigureNo(data.get(i).get(10).toString());
                tool.setFileName(data.get(i).get(11).toString());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//yyyy-mm-dd, 会出现时间不对, 因为小写的mm是代表: 秒
                Date EnterFactoryDate = sdf.parse(data.get(i).get(12).toString());
                tool.setEnterFactoryDate(EnterFactoryDate);
                String checkDate = data.get(i).get(13).toString();
                if (StringUtils.isNotBlank(checkDate)) {
                    tool.setCheckDate(dayFormat.parse(checkDate));
                }
                tool.setCheckReportNo(data.get(i).get(14).toString());
                String scrapDate = data.get(i).get(15).toString();
                if (StringUtils.isNotBlank(scrapDate)) {
                    tool.setScrapDate(dayFormat.parse(scrapDate));
                }
                tool.setRepairType(data.get(i).get(16).toString());
                tool.setCheckoutFlag(data.get(i).get(17).toString());
                String checkoutDate = data.get(i).get(18).toString();
                if (StringUtils.isNotBlank(checkoutDate)) {
                    tool.setCheckoutDate(dayFormat.parse(checkoutDate));
                    tool.setNextCheckoutDate(dayFormat.parse(checkoutDate));
                }
                if (data.get(i).get(19)!=null||StringUtils.isNotBlank(data.get(i).get(19).toString())) {
                    tool.setCheckoutCycle(Double.valueOf(data.get(i).get(19).toString()));
                }
                tool.setMaintainFlag(data.get(i).get(20).toString());
                String maintainDate = data.get(i).get(21).toString();
                if (StringUtils.isNotBlank(maintainDate)) {
                    tool.setMaintainDate(dayFormat.parse(maintainDate));
                    tool.setNextMaintainDate(dayFormat.parse(maintainDate));
                }
                if (data.get(i).get(22)!=null||StringUtils.isNotBlank(data.get(i).get(22).toString())) {
                    tool.setMaintainCycle(Double.valueOf(data.get(i).get(22).toString()));
                }
                //TODO 批量插入
                ttEqToolDao.insert(tool);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传文件出错");
        } catch (ParseException e1) {
            e1.printStackTrace();
            throw new ServiceException("第"+errorRow+"行日期格式转换出错");
        } catch (IndexOutOfBoundsException e2) {
            e2.printStackTrace();
            throw new ServiceException("第"+errorRow+"行存在空值");
        }
    }

    @Resource
    private TmProductModelDao tmProductModelDao;

    @Override
    public List<TmProductModel> findProductModel(String search) {
        EntityWrapper<TmProductModel> ew = new EntityWrapper<>();
        ew.setSqlSelect("pk_id","prod_model","prod_model_code");
        if (StringUtils.isNotBlank(search)) {
            ew.andNew().like("prod_model",search).or().like("prod_model_code",search);
        }
        return tmProductModelDao.selectList(ew);
    }
}
